<template>
  <div class="custom-table">
    <div
      style="border: 1px solid #e4e7ed; border-radius: 8px; margin-bottom: 10px"
    >
      <!-- 顶部操作栏 -->
      <div class="header-section">
        <h3>查验项目</h3>
        <div class="action-buttons" v-if="props.activeName_1 != '2'">
          <el-button type="primary" plain @click="setActiveType('1')">
            检查
          </el-button>
          <el-button type="primary" plain @click="setActiveType('2')">
            检验
          </el-button>
        </div>
      </div>
      <!-- 表头 -->
      <div class="table-header">
        <div
          v-for="column in props.columns"
          :key="column.key"
          class="header-cell"
          :style="{
            width: column.flex ? undefined : column.width,
            flex: column.flex ? 1 : undefined,
            textAlign: column.align || 'left',
          }"
        >
          {{ column.label }}
        </div>
      </div>

      <!-- 表格数据行 -->
      <div
        v-for="(row, index) in displayTableData"
        :key="row.examId"
        class="table-row-container"
        :class="{ 'add-row': row.isNew }"
      >
        <div class="table-row" :class="{ 'add-row': row.isNew }">
          <div
            v-for="column in props.columns"
            :key="column.key"
            class="table-cell"
            :style="getColumnStyle(column)"
          >
            <!-- 序号列 -->
            <template v-if="column.key === 'index'">
              {{ row.isNew ? '' : index + 1 }}
            </template>

            <!-- 项目列 -->
            <template v-else-if="column.key === 'name'">
              <span>{{ row.projectName }}</span>
            </template>

            <!-- 类别列 -->
            <template v-else-if="column.key === 'category'">
              {{ row.projectCategoryName }}
            </template>

            <!-- 频率列 -->
            <template v-else-if="column.key === 'frequency'">
              <el-select
                v-model="row.frequencyCode"
                filterable
                style="width: 100px"
                class="borderless-select"
                suffix-icon=""
                @change="onFrequency(row, index)"
                v-if="props.activeName_1 != '2'"
              >
                <el-option
                  v-for="frequency in frequencyOptions"
                  :key="frequency.frequencyCode"
                  :label="frequency.frequencyName"
                  :value="frequency.frequencyCode"
                />
              </el-select>

              <span v-else>{{ row.frequencyCodeText }}</span>
            </template>

            <!-- 周期列 -->
            <template v-else-if="column.key === 'period'">
              <div
                style="
                  display: flex;
                  align-items: center;
                  gap: 8px;
                  position: relative;
                "
              >
                <el-input-number
                  v-model="row.cycle"
                  :min="0"
                  :max="999"
                  :controls="false"
                  class="borderless-input"
                  style="width: 50px"
                  @change="updateRow(row, index)"
                  @focus="showKeyboard(row, index, 'cycle')"
                  @click.stop
                  v-if="props.activeName_1 != '2'"
                />
                <span v-else>{{ row.cycle }}</span>
                <span>{{ row.cycleUnitText }}</span>

                <!-- 数字键盘 -->
                <div
                  v-if="
                    keyboardVisible &&
                    currentEditRow === row &&
                    currentEditField === 'cycle'
                  "
                  class="number-keyboard"
                  @click.stop
                >
                  <NumericKeyboardInt
                    @input="inputNumber"
                    @delete="deleteNumber"
                  />
                </div>
              </div>
            </template>

            <!-- 总量列 -->
            <template v-else-if="column.key === 'totalCount'">
              <div
                style="
                  display: flex;
                  align-items: center;
                  gap: 4px;
                  position: relative;
                "
              >
                <el-input-number
                  v-model="row.totalOutQty"
                  :min="0"
                  :max="999"
                  :controls="false"
                  class="borderless-input"
                  ref="searchInputRef"
                  style="width: 50px"
                  @change="updateRow(row, index)"
                  @focus="showKeyboard(row, index, 'totalOutQty')"
                  @click.stop
                  v-if="props.activeName_1 != '2'"
                />
                <span v-else>{{ row.totalOutQty }}</span>
                <div>{{ row.totalOutQtyUnitText || ' ' }}</div>

                <!-- 总量数字键盘 -->
                <div
                  v-if="
                    keyboardVisible &&
                    currentEditRow === row &&
                    currentEditField === 'totalOutQty'
                  "
                  class="number-keyboard"
                  @click.stop
                >
                  <NumericKeyboardInt
                    @input="inputNumber"
                    @delete="deleteNumber"
                  />
                </div>
              </div>
            </template>

            <!-- 备注列 -->
            <template v-else-if="column.key === 'remark'">
              <!-- <el-input
              v-model="row.remark"
              style="width: calc(100% - 30px)"
              class="no-border-input"
              placeholder="请输入备注"
              @change="updateRow(row, index)"
              v-if="props.activeName_1 != '2'"
            />
            <span v-else>{{ row.remark }}</span>
            <el-button
              v-if="row.isNew"
              type="primary"
              text
              size="small"
              style="margin-left: 8px"
              @click="confirmAdd(row, index)"
            >
              +
            </el-button> -->

              <AutocompleteMulti
                v-model="row.remark"
                class="borderless-select right-select"
                placeholder=""
                :trigger-on-focus="true"
                :fetch-suggestions="querySearchAsync"
                :selected-color="'#16ada4'"
                v-if="props.activeName_1 != '2'"
                @update:modelValue="
                  (val) => {
                    //console.log('update:', val);
                    row.remark = val;
                  }
                "
              />
              <span v-else>{{ row.remark }}</span>
            </template>

            <!-- 自定义列 -->
            <template v-else>
              {{ row[column.key as keyof any] }}
            </template>
          </div>
        </div>

        <!-- 悬浮删除按钮 -->
        <div
          class="delete-button"
          @click="deleteRow(row, index)"
          v-if="props.activeName_1 != '2'"
        >
          <img src="@/assets/manage/icon_off_hover.svg" alt="删除" />
        </div>
      </div>
      <!-- 搜索行 -->
      <div class="table-row search-row" v-if="props.activeName_1 != '2'">
        <div
          v-for="(column, columnIndex) in props.columns"
          :key="`search-${column.key}`"
          class="table-cell"
          :style="{
            border: columnIndex === 0 ? 'none' : undefined,
            position: columnIndex === 0 ? 'relative' : undefined,
          }"
        >
          <template v-if="columnIndex === 0">
            <div
              class="table-row"
              style="font-size: 16px; color: #999999; line-height: 35px"
            >
              +
            </div>
            <el-input
              v-model="searchText"
              placeholder="搜索项目名称或拼音缩写"
              class="search-input"
              style="width: 100%"
              clearable
              @input="handleSearch"
              @focus="showSearchKeyboard"
              @click.stop
            />

            <!-- 搜索全键盘 -->
            <div v-if="searchKeyboardVisible" @click.stop>
              <!-- 数字行 (所有模式都显示) -->
              <SearchKeyboard
                :mode="keyboardMode"
                @input="(result) => inputSearchChar(result)"
                @delete="deleteSearchChar()"
                @clear="clearSearch"
                @switch="switchKeyboard"
              />
            </div>

            <!-- 搜索结果下拉列表 -->
            <div
              v-if="searchResults.length > 0 && searchText"
              class="search-results"
              @click.stop
            >
              <div class="table-header">
                <div
                  class="header-cell"
                  style="width: 620px; text-align: left; padding-left: 16px"
                >
                  项目
                </div>
                <div
                  class="header-cell"
                  style="width: 100px; text-align: left; padding-left: 16px"
                >
                  类别
                </div>
                <div
                  class="header-cell"
                  style="width: 100px; text-align: left; padding-left: 16px"
                >
                  规格
                </div>
                <div
                  class="header-cell"
                  style="width: 100px; text-align: left; padding-left: 16px"
                >
                  单价
                </div>
              </div>
              <div
                v-for="result in searchResults"
                :key="result.projectId"
                class="search-result-item"
                @click="selectSearchResult(result)"
              >
                <div
                  class="result-name"
                  style="width: 620px; text-align: left; padding-left: 16px"
                >
                  {{ result.projectName }}
                </div>
                <div
                  class="result-category"
                  style="width: 100px; text-align: left; padding-left: 16px"
                >
                  {{ result.projectCategoryName }}
                </div>
                <div
                  class="result-spec"
                  style="width: 100px; text-align: left; padding-left: 16px"
                >
                  {{ result.unitName }}
                </div>
                <div
                  class="result-price"
                  style="width: 100px; text-align: left; padding-left: 16px"
                >
                  ¥ {{ (result.price / 100).toFixed(2) }}
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
// import AutocompleteMulti from '@/components/AutocompleteMulti.vue';
import { ElMessage } from 'element-plus';
import { getFeeStandardList } from '@/api/formwork';
import { v4 as uuidv4 } from 'uuid';
import stores from '@/store';
const useBaseDataStore = stores.useBaseDataStore();
const searchKeyboardOnTop = ref(false);
const searchInputRef = ref<HTMLInputElement | null>(null);
// 定义数据类型
// interface any {
//   examId: number;
//   projectId: number; // 主键ID
//   projectName: string; // 项目名称;CT
//   price: number; // 价格
//   projectCategory: string; // 项目分类;1检查2.检验3.治疗 projectCategoryEnum
//   projectCategoryName: string; // 项目分类名称
//   projectType: string; // 项目类型;头部CT 如果projectCategory=1取字典中的EXAM_TYPE,projectCategory=2取LAB_TYPE，如果等于3取EXT_TYPE
//   sampleType: string; // 样本类型;如果是检验项目需要维护1.全血 sampleTypeEnum
//   chargeType: string; // 收费类型1项目2穴位 ProjectChargeTypeEnum
//   unit: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
//   unitName: string; // 单位;次 取字典接口中key=UNIT并且unitType=2的数据
//   isNew?: boolean;
//   remark?: string;
//   frequencyCode?: string; // 频率代码
//   frequencyName?: string; // 频率名称
// }

// 定义表头列类型
interface TableColumn {
  key: string;
  label: string;
  width?: string;
  flex?: boolean;
  align?: 'left' | 'center' | 'right';
}

// Props
interface Props {
  title?: string;
  tableData?: any[];
  frequencyOptions?: Array<any>;
  defaultActiveType?: 'inspection' | 'examination';
  columns?: TableColumn[];
  activeName_1?: string;
}

const props = withDefaults(defineProps<Props>(), {
  title: '查验项目',
  tableData: () => [],
  frequencyOptions: () => [],
  defaultActiveType: 'inspection',
  columns: () => [
    { key: 'index', label: '序号', width: '80px', align: 'center' },
    { key: 'name', label: '项目', width: '150px' },
    { key: 'category', label: '类别', width: '109px' },
    { key: 'frequency', label: '频率', width: '140px' },
    { key: 'period', label: '周期', width: '130px' },
    { key: 'totalCount', label: '总量', width: '100px' },
    { key: 'remark', label: '备注', flex: true },
  ],
  activeName_1: '',
});

// Emits
const emit = defineEmits<{
  'update:tableData': [value: any[]];
  'active-type-change': [type: any];
  'row-update': [row: any, index: number];
  'search-result-select': [result: any];
}>();

// 响应式数据
const activeType = ref<any>(props.defaultActiveType);
const searchText = ref('');
const searchKeyboardVisible = ref(false);
const keyboardMode = ref<'english' | 'chinese'>('english');
const searchResults = ref<any[]>([]);

// 数字键盘相关
const keyboardVisible = ref(false);
const currentEditRow = ref<any | null>(null);
const currentEditField = ref<'cycle' | 'totalOutQty' | null>(null);

// 获取列的样式
const getColumnStyle = (column: TableColumn) => {
  return {
    width: column.flex ? undefined : column.width,
    flex: column.flex ? 1 : undefined,
    textAlign: column.align || 'left',
  };
};
const displayTableData = ref<any[]>([]);
// 深度差异比较函数
function getDeepChanges(newObj: any[], oldObj: any[], path = '') {
  if (!oldObj) return [{ path, newValue: newObj }];

  if (Array.isArray(newObj)) {
    const changes: any[] = [];
    newObj.forEach((item, index) => {
      changes.push(...getDeepChanges(item, oldObj[index], `${path}[${index}]`));
    });
    return changes;
  }

  return newObj !== oldObj
    ? [{ path, oldValue: oldObj, newValue: newObj }]
    : [];
}
function extractDifferences(changeItems: any[]) {
  // 深度比较两个值是否相等
  function isDeepEqual(
    a: { [x: string]: any } | null,
    b: { [x: string]: any } | null
  ) {
    if (a === b) return true;
    if (
      typeof a !== 'object' ||
      a === null ||
      typeof b !== 'object' ||
      b === null
    )
      return false;

    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;

    for (const key of keysA) {
      if (!keysB.includes(key)) return false;
      if (!isDeepEqual(a[key], b[key])) return false;
    }
    return true;
  }

  return changeItems
    .map((item) => {
      const { path, oldValue, newValue } = item;
      const uuid = newValue?.uuid || oldValue?.uuid; // 获取UUID

      const changedFields: any = {};

      // 收集所有key，包括oldValue和newValue中的
      const allKeys = new Set([
        ...Object.keys(oldValue || {}),
        ...Object.keys(newValue || {}),
      ]);

      // 比较每个字段
      for (const key of allKeys) {
        const oldVal = oldValue?.[key];
        const newVal = newValue?.[key];
        // 只有当值确实不同时才记录
        if (!isDeepEqual(oldVal, newVal)) {
          changedFields[key] = {
            old: oldVal,
            new: newVal,
            uuid: uuid,
          };
        }
      }

      // 只返回有实际变化的项
      return Object.keys(changedFields).length > 0
        ? { path, changes: changedFields, uuid }
        : null;
    })
    .filter(Boolean); // 过滤掉没有实际变化的项
}
// 计算属性：过滤后的表格数据
watch(
  () => props.tableData,
  (newVal) => {
    displayTableData.value = newVal.map((item) => ({
      ...item,
      uuid: uuidv4(),
      projectCategoryName: useBaseDataStore.getEnumData(
        item.projectCategory,
        'projectCategoryEnum'
      ),
    }));
  },
  { immediate: true }
);

// 计算总量：频率(次数/天等) * 周期(天数) => totalOutQty
const recalcRowTotal = (row: any) => {
  if (!row) return;
  const freqCode = row.frequencyCode;
  const cycle = Number(row.cycle);
  if (!freqCode || !cycle || isNaN(cycle)) return;
  const freq = props.frequencyOptions?.find(
    (f: any) => f.frequencyCode === freqCode
  );
  const times = Number(freq?.frequencyTimes);
  // if (!freq || isNaN(times) || times <= 0) return;
  const computedTotal = times * cycle;
  if (row.totalOutQty !== computedTotal) {
    row.totalOutQty = computedTotal;
  }
};

// 监听频率与周期变化（仅采集必要字段，避免深度 watch 性能损耗）
watch(
  () =>
    displayTableData.value.map((r) => ({
      id: r.examId,
      f: r.frequencyCode,
      c: r.cycle,
      uuid: r.uuid,
    })),
  (newSnap, oldSnap) => {
    const diffs = extractDifferences(getDeepChanges(newSnap, oldSnap));
    //console.log('实际变化的字段:', diffs);
    const changedUUIDs = diffs.map((diff: any) => diff.uuid).filter(Boolean);
    //console.log(changedUUIDs);
    displayTableData.value.forEach((item) => {
      if (
        currentEditField.value == 'cycle' &&
        changedUUIDs.includes(item.uuid)
      ) {
        if (item.cycle) {
          const frequencyTimes = props.frequencyOptions?.find(
            (freq: { frequencyCode: any }) =>
              freq.frequencyCode === item.frequencyCode
          )?.frequencyTimes;
          item.totalOutQty = item.cycle * frequencyTimes;
        } else {
          item.totalOutQty = null;
        }
      }
    });
    //console.log(displayTableData.value);

    // displayTableData.value.forEach(recalcRowTotal);
  },
  { deep: false }
);
// frequency.value?.find(
//         (freq: { frequencyCode: any }) =>
//           freq.frequencyCode === item.frequencyCode
//       )?.frequencyTimes
// 方法
const setActiveType = (type: string) => {
  activeType.value = type;
  emit('active-type-change', type);
};

const updateRow = (row: any, index: number) => {
  //console.log(row);

  emit('row-update', row, index);
};
const querySearchAsync = (queryString: string, cb: any) => {
  const data1 = useBaseDataStore.getDictsSelect('REMARK') || [];
  // 仅保留 rxType 为 5 的项（兼容数字/字符串）
  const filtered = (Array.isArray(data1) ? data1 : []).filter(
    (item: any) => item?.rxType === 5 || item?.rxType === '5'
  );
  const results = filtered.map((item: any) => ({
    value: item.remarkText,
    ...item,
  }));
  cb(results);
};
const onFrequency = (row: any, index: number) => {
  const selectedFrequency = props.frequencyOptions?.find(
    (freq) => freq.frequencyCode === row.frequencyCode
  );
  if (selectedFrequency) {
    row.cycleUnit = selectedFrequency.cycleUnit;
    row.cycleUnitText = useBaseDataStore.getEnumData(
      selectedFrequency.cycleUnit,
      'cycleUnitEnum'
    );
    updateRow(row, index);
  }
};
// 获取单位名称的方法
const getUnitName = (unitCode: string) => {
  const UNITDATA = useBaseDataStore.getDictsSelect('UNIT') || [];
  // 过滤出unitType等于2的数据
  const filteredUnits = UNITDATA.filter(
    (unit: any) => unit.unitType === '2' || unit.unitType === 2
  );
  // 根据unitCode查找对应的单位名称
  const foundUnit = filteredUnits.find(
    (unit: any) => unit.unitCode === unitCode
  );
  //console.log(foundUnit);

  return foundUnit ? foundUnit.unitText : unitCode; // 如果找不到就返回原始unitCode
};

// 搜索方法
const handleSearch = async (value: string) => {
  //console.log('搜索内容:', value);

  // 调用API获取搜索结果数据
  if (value && value.trim()) {
    const result = await getFeeStandardList({ projectName: value });
    searchResults.value =
      result?.data.map((item: any) => ({
        projectId: item.projectId,
        projectName: item.projectName,
        price: item.price,
        projectCategory: item.projectCategory,
        projectCategoryName: useBaseDataStore.getEnumData(
          item.projectCategory,
          'projectCategoryEnum'
        ),
        projectType: item.projectType,
        sampleType: item.sampleType || '',
        chargeType: item.chargeType,
        unit: item.unit,
        unitName: getUnitName(item.unit), // 使用新的方法获取单位名称
      })) || [];
  } else {
    searchResults.value = [];
  }
};

// 搜索键盘相关方法
const showSearchKeyboard = () => {
  searchKeyboardVisible.value = true;
  document.addEventListener('keydown', handleKeyboardShortcut);
};

const hideSearchKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (
      target.closest('.search-keyboard') ||
      target.closest('.search-results') ||
      target.closest('.search-input')
    ) {
      return;
    }
  }

  searchKeyboardVisible.value = false;
  document.removeEventListener('keydown', handleKeyboardShortcut);
};

const handleKeyboardShortcut = (event: KeyboardEvent) => {
  if (event.ctrlKey && event.shiftKey && event.key === 'T') {
    event.preventDefault();
    switchKeyboard();
  } else if (event.key === 'Escape') {
    event.preventDefault();
    hideSearchKeyboard();
  }
};

const inputSearchChar = (char: string) => {
  searchText.value += char;
  handleSearch(searchText.value);
};

const deleteSearchChar = () => {
  if (searchText.value.length > 0) {
    searchText.value = searchText.value.slice(0, -1);
    handleSearch(searchText.value);
  }
};

const clearSearch = () => {
  searchText.value = '';
  searchResults.value = [];
};

const switchKeyboard = () => {
  if (keyboardMode.value === 'english') {
    keyboardMode.value = 'chinese';
  } else if (keyboardMode.value === 'chinese') {
    keyboardMode.value = 'english';
  }
};

const selectSearchResult = (result: any) => {
  //console.log('选择了:', result);

  // 将搜索结果转换为 any 格式
  const newItem: any = {
    examId: Date.now(),
    name: result.projectName,
    category: activeType.value === '2' ? '检验' : '检查',
    frequency: '',
    cycle: 1,
    totalOutQty: 1,
    frequencyCode: 'qd',
    cycleUnit: 'day',
    cycleUnitText: '天',
    projectId: result.projectId,
    projectName: result.projectName,
    price: result.price,
    projectCategory: result.projectCategory,
    projectCategoryName: result.projectCategoryName,
    projectType: result.projectType,
    sampleType: result.sampleType,
    chargeType: result.chargeType,
    unit: result.unit,
    unitName: result.unitName,
    remark: result.instrs,
    totalOutQtyUnitText: result.unitName,
  };

  // 通过 emit 更新父组件的数据
  const updatedData = [...displayTableData.value, newItem];
  emit('update:tableData', updatedData);

  ElMessage.success(`已选择: ${result.projectName}`);
  searchKeyboardVisible.value = false;
  searchResults.value = [];
  searchText.value = '';
  emit('search-result-select', result);
};

// 数字键盘相关方法
const showKeyboard = (
  row: any,
  index: number,
  field: 'cycle' | 'totalOutQty'
) => {
  currentEditRow.value = row;
  currentEditField.value = field;
  keyboardVisible.value = true;

  // 确保字段有初始值
  if (row[field] === undefined || row[field] === null) {
    row[field] = null;
    //console.log('showKeyboard: initialized field value to 1', field);
  }
};

const hideKeyboard = (event?: Event) => {
  if (event && event.target) {
    const target = event.target as Element;
    if (target.closest('.number-keyboard')) {
      return;
    }
  }

  keyboardVisible.value = false;
  currentEditRow.value = null;
  currentEditField.value = null;
};

const inputNumber = (num: string) => {
  if (!currentEditRow.value || !currentEditField.value) {
    return;
  }

  // 获取当前值，如果不存在则使用默认值
  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    if (currentEditField.value === 'cycle') {
      const data = props.frequencyOptions.find(
        (item: any) =>
          item.frequencyCode === currentEditRow.value['frequencyCode']
      );
      currentEditRow.value['totalOutQty'] = data.frequencyTimes * parseInt(num);
    }
    // 设置默认值
    currentEditRow.value[currentEditField.value] = parseInt(num);
    return;
  }

  const currentValueStr = currentValue.toString();
  const newValue = parseInt(currentValueStr + num);

  const maxValue = currentEditField.value === 'cycle' ? 999 : 999;
  if (newValue <= maxValue) {
    currentEditRow.value[currentEditField.value] = newValue;
    if (currentEditField.value === 'cycle') {
      const data = props.frequencyOptions.find(
        (item: any) =>
          item.frequencyCode === currentEditRow.value['frequencyCode']
      );
      currentEditRow.value['totalOutQty'] = data.frequencyTimes * newValue;
    }
  } else {
  }
};

const deleteNumber = () => {
  if (!currentEditRow.value || !currentEditField.value) {
    //console.log('deleteNumber: currentEditRow or currentEditField is null');
    return;
  }

  const currentValue = currentEditRow.value[currentEditField.value];
  if (currentValue === undefined || currentValue === null) {
    //console.log('deleteNumber: current value is undefined/null');
    return;
  }

  const currentValueStr = currentValue.toString();
  const newValue = currentValueStr.slice(0, -1);
  currentEditRow.value[currentEditField.value] =
    newValue === '' ? null : parseInt(newValue);
};
const confirmAdd = (row: any, index: number) => {
  if (!row.projectName.trim()) {
    ElMessage.warning('请选择项目');
    return;
  }

  // const newItem: any = {
  //   id: Date.now(),
  //   name: row.name,
  //   category: activeType.value === 'inspection' ? '检验' : '检查',
  //   frequency: row.frequency,
  //   period: row.period,
  //   totalCount: row.totalCount,
  //   remark: row.remark || '新添加项目',
  // };

  // const updatedData = [...props.tableData, newItem];
  // emit('update:tableData', updatedData);
  // ElMessage.success('项目添加成功');
};

// 删除行方法
const deleteRow = (row: any, index: number) => {
  const updatedData = displayTableData.value.filter(
    (item) => item.examId !== row.examId
  );
  emit('update:tableData', updatedData);
  ElMessage.success('项目删除成功');
};

// 生命周期钩子
const globalClickHandler = (event: Event) => {
  hideKeyboard(event);
  hideSearchKeyboard(event);
};
onMounted(() => {
  document.addEventListener('mousedown', globalClickHandler);
});
onUnmounted(() => {
  document.removeEventListener('mousedown', globalClickHandler);
});
defineExpose({
  displayTableData,
});
</script>

<style lang="scss" scoped>
// 自定义表格样式
.custom-table {
  width: 100%;
  position: relative;
  margin-top: 10px;
  background-color: #fff;
  border-radius: 8px;
  .header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 16px 20px;

    h3 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }

    .action-buttons {
      display: flex;

      .el-button.active {
        background-color: #409eff;
        color: white;
        border-color: #409eff;
      }
    }
  }

  .table-header {
    display: flex;
    background-color: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;

    .header-cell {
      padding: 12px 8px;
      text-align: center;
      font-weight: 600;
      color: #909399;
      font-size: 14px;
      border-right: none;
      align-items: center;
    }
  }

  .table-row-container {
    position: relative;
    display: flex;
    align-items: center;
    &:hover {
      .delete-button {
        opacity: 1;
        visibility: visible;
      }
    }

    .table-row {
      flex: 1;
      display: flex;
      border-bottom: 1px solid #e4e7ed;

      &:last-child {
        border-bottom: none;
      }

      // &:hover {
      //   background-color: #f5f7fa;
      // }

      &.add-row {
        background-color: #fafafa;
      }

      .table-cell {
        padding: 12px 8px;
        align-items: center;
        border-right: none;
        height: 50px;
        position: relative;

        &:last-child {
          justify-content: flex-start;
          padding-left: 12px;
        }

        &:has(.number-keyboard) {
          overflow: visible;
          z-index: 1;
        }
      }
    }

    .delete-button {
      position: absolute;
      right: -18px;
      top: 55%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #989898;
      border-radius: 50%;
      cursor: pointer;
      opacity: 0;
      visibility: collapse;
      transition: all 0.3s ease;
      z-index: 10;

      &:hover {
        transform: translateY(-50%) scale(1.1);
      }

      img {
        width: 16px;
        height: 16px;
        filter: brightness(0) invert(1); // 将图标变为白色
      }
    }
  }

  .table-row {
    display: flex;
    // border-bottom: 1px solid #e4e7ed;
  }
}

// 无边框输入框样式
:deep(.borderless-select) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
  }

  // &:hover .el-input__wrapper {
  //   border-color: #c0c4cc;
  // }

  &.is-focus .el-input__wrapper {
    border-color: #409eff;
  }
}

:deep(.borderless-input) {
  .el-input__wrapper {
    border: 1px solid #dcdfe6;
    box-shadow: none;
  }

  &:hover .el-input__wrapper {
    border-color: #c0c4cc;
  }

  &.is-focus .el-input__wrapper {
    border-color: #409eff;
  }
}

:deep(.no-border-input) {
  .el-input__wrapper {
    box-shadow: none;
    padding: 0;
  }
}

// 数字键盘样式
.number-keyboard {
  position: absolute;
  top: 60%;
  left: 0;
  z-index: 9999 !important;
  border-radius: 8px;
  padding: 8px;
  margin-top: 4px;
  transform: translateZ(0);

  .keyboard-row {
    display: flex;
    gap: 4px;
    margin-bottom: 4px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    width: 50px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #f8f9fa;
    color: #333;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      width: 104px;
      background: #f56c6c;
      color: white;
      font-size: 14px;

      &:hover {
        background: #f78989;
      }
    }
  }
}

// 搜索行样式
.search-row {
  .table-cell {
    padding: 12px 8px;
    text-align: left;
    display: flex;
    align-items: center;
    border-right: none;
    height: 50px;
    position: relative;
    justify-content: flex-start;
    &:first-child {
      padding-left: 17px;
      display: flex;
      width: 100%;
    }
  }

  .search-input {
    :deep(.el-input__wrapper) {
      background-color: transparent;
      box-shadow: none;
      border-radius: 4px;
    }

    :deep(.el-input__inner) {
      font-weight: 500;

      &::placeholder {
        font-weight: normal;
      }
    }

    :deep(.el-input__prefix) {
      color: #f87171;
    }
  }
}

// 搜索键盘样式
.search-keyboard {
  position: absolute;
  top: -220px;
  left: 0;
  z-index: 9999;
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25);
  width: 600px;
  max-width: 90vw;

  .keyboard-row {
    display: flex;
    gap: 6px;
    margin-bottom: 8px;
    justify-content: center;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .key-btn {
    min-width: 45px;
    height: 40px;
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    background: #ffffff;
    color: #333;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 8px;

    &:hover {
      background: #e9ecef;
      border-color: #409eff;
    }

    &:active {
      background: #dee2e6;
      transform: scale(0.95);
    }

    &.delete-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.clear-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.switch-btn {
      color: rgb(0, 0, 0);
      min-width: 60px;
    }

    &.space-btn {
      min-width: 60px;
      color: rgb(0, 0, 0);
    }
  }
}

// 搜索结果样式
.search-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9998;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  margin-top: 4px;
  max-height: 300px;
  overflow-y: auto;
  width: 100%;

  // 重写搜索结果中的表头样式，确保与内容对齐
  .table-header {
    .header-cell {
      text-align: left !important;
      justify-content: flex-start !important;
    }
  }

  .search-result-item {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #f5f7fa;
    cursor: pointer;
    text-align: left;
    transition: background-color 0.2s;
    height: 48px; // 设置固定高度

    &:last-child {
      border-bottom: none;
    }

    &:hover {
      background-color: #f0f9ff;
    }

    // 清除子元素样式，使用内联样式控制
    .result-name,
    .result-category,
    .result-spec,
    .result-price {
      display: flex;
      align-items: center;
      height: 100%;
      font-size: 14px;
      color: #333;
    }

    .result-category,
    .result-spec {
      font-size: 12px;
      color: #666;
    }

    .result-price {
      font-weight: 600;
    }
  }
}
::v-deep(.el-input__wrapper) {
  padding-left: 5px !important;
  padding-right: 5px !important;
}
</style>
